package sort.impl;

import anaydis.sort.SorterType;
import anaydis.sort.gui.SorterListener;
import com.sun.istack.internal.NotNull;

import java.util.Comparator;
import java.util.List;

public class QuickSorterCutOff extends AbstractQuickSorter {
    private int M;
    private InsertionSorter insertionSorter;

    public QuickSorterCutOff() {
        super(SorterType.QUICK_CUT);
        insertionSorter = new InsertionSorter();
        M = 9;
    }

    public void setM(int M) {
        this.M = M;
    }

    public <T> void sort(@NotNull Comparator<T> tComparator, @NotNull List<T> ts) {
        sort(tComparator, ts, 0, ts.size() - 1);
        for (SorterListener sorterListener : sorterListeners) {
                insertionSorter.addSorterListener(sorterListener);
        }
    }

    private <T> void sort(Comparator<T> tComparator, List<T> ts, int left, int right) {
        if (right <= left) return;
        if ((right-left) > M) {
            int i = partition(tComparator, ts, left, right);
            sort(tComparator, ts, left, i - 1);
            sort(tComparator, ts, i+1, right);
        } else {
            insertionSorter.sort(tComparator, ts, left, right+1);
        }
    }

    public int getM() {
        return M;       
    }
}
